package  common.utils
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class ScrollUtil 
	{
		// 可视角的左上角点
		private var newX:Number;   
		private var newY:Number;
				
		private var followHeight:Number;  // 滚屏的最大高度
		private var followWidth:Number;   // 滚屏的最大宽度
		
		private var _viewSize:Rectangle;  // 显示的矩形区域
		
		private var m_target : DisplayObject;
		
		public function ScrollUtil()
		{
			
			
		}
		
		/**
		 * 绑定滚动 
		 * @param target  		目标
		 * @param viewRect  	可视矩形区域
		 * @param width   		滚屏宽度
		 * @param height 	 	滚屏高度
		 * 
		 */		
		public function bind(target:DisplayObject,viewRect:Rectangle,width:Number,height:Number) : void
		{
			followHeight = height;
			followWidth = width;
			_viewSize = viewRect;
			m_target = target;
		}
		
		/**
		 * 销毁 
		 */		
		public function destory() : void
		{
			newX = 0;
			newY = 0;
			followHeight = 0;
			followWidth = 0;
			_viewSize = null;
			m_target = null;
		}
		
		public function set viewSize(param1:Rectangle) : void
		{
			_viewSize = param1;
			return;
		}
		
		public function get viewSize() : Rectangle
		{
			return _viewSize;
		}
		
		/**
		 *获取计算后的逻辑位置 
		 * @return 
		 * 
		 */		
		public function getPoint() : Point
		{
			var _loc_2:* = new Point();
			_loc_2.x = int(newX - _viewSize.width / 2);
			_loc_2.y = int(newY - _viewSize.height / 2);
			return _loc_2;
		}
		
		/**
		 *滚屏移动 
		 * @param vx
		 * @param vy
		 * 
		 */		
		public function move(vx:Number, vy:Number) : void
		{
			m_target.x = m_target.x - vx;
			m_target.y = m_target.y - vy;
			if (m_target.x > 0)
			{
				m_target.x = 0;
			}
			if (m_target.y > 0)
			{
				m_target.y = 0;
			}
			
			if (m_target.x < _viewSize.width - followWidth)
			{
				m_target.x = _viewSize.width - followWidth;
			}
			if (m_target.y < _viewSize.height - followHeight)
			{
				m_target.y = _viewSize.height - followHeight;
			}
		}
		
		/**
		 *移动到某点 
		 * @param px
		 * @param py
		 * 
		 */		
		public function moveTo(px:Number, py:Number) : void
		{
			newX = px;
			newY = py;
			
			checkRectangle();
			
			m_target.x = int(-getPoint().x);
			m_target.y = int(-getPoint().y);
		}
		
		/**
		 * 计算当前对象可视角左上角位置 
		 */		
		private function checkRectangle() : void
		{
			if (newX < int(_viewSize.width / 2))
			{
				newX = int(_viewSize.width / 2);
			}
			if (newY < int(_viewSize.height / 2))
			{
				newY = int(_viewSize.height / 2);
			}
			if (newX > int(followWidth - _viewSize.width / 2))
			{
				newX = int(followWidth - _viewSize.width / 2);
			}
			if (newY > int(followHeight - _viewSize.height / 2))
			{
				newY = int(followHeight - _viewSize.height / 2);
			}
		}
	}
}
